package com.sddfp.sys.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.sddfp.common.constant.redis.RedisConstant;
import com.sddfp.sys.config.SmsTemplate;
import com.sddfp.sys.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendCode(String phone) {
        // 验证码还没有过期，直接返回
        if (stringRedisTemplate.hasKey(RedisConstant.SMS_PREFIX + phone)){
            return;
        }
        String code = RandomUtil.randomNumbers(4);
        log.info("验证码：{}",code);
        // 验证码存储到redis
        stringRedisTemplate.opsForValue().set(RedisConstant.SMS_PREFIX + phone,code, Duration.ofMinutes(5));
        // 调用阿里云sms服务，发送验证码
        smsTemplate.sendSms(phone,code);
    }
}
